package com.csap.framework.boot.apidoc.autoconfigure;

import com.csap.framework.core.BeanDefinitionRegistrar;
import com.csap.framework.util.CollectionsUtil;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;

/**
 * @author yangchengfu
 * @description 自定义 注册
 * @dataTime 2020年-09月-22日 13:30:00
 **/
@Component
public class ApidocImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, BeanDefinitionRegistrar, BeanFactoryAware {
    @Getter
    private BeanFactory beanFactory;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(EnableApidoc.class.getName());
        if (annotationAttributes != null) {
            EnableApidocConfig csapDocConfig = registerBean(beanFactory, registry, EnableApidocConfig.class);
            String[] apiPackages = (String[]) annotationAttributes.get("apiPackages");
            String[] enumPackages = (String[]) annotationAttributes.get("enumPackages");
            String[] modelPackages = (String[]) annotationAttributes.get("modelPackages");
            if (CollectionsUtil.isNotEmpty(apiPackages)) {
                csapDocConfig.getApiPackages().addAll(Arrays.asList(apiPackages));
            }
            if (CollectionsUtil.isNotEmpty(enumPackages)) {
                csapDocConfig.getEnumPackages().addAll(Arrays.asList(enumPackages));
            }
            if (CollectionsUtil.isNotEmpty(modelPackages)) {
                csapDocConfig.getModelPackages().addAll(Arrays.asList(modelPackages));
            }
        }
    }


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

}
